//
//  HBMyBankReleaseCtrl.m
//  HuoBao
//
//  Created by chaiyanan on 15/12/7.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBMyBankReleaseCtrl.h"
#import "CheckValid.h"

#import "HBDisbindBankCardInfo.h"
#import "HBDisbindBankCardParam.h"
#import "HBDisbindBankCardParser.h"

#import "HBDisbindBankCardConfirmParam.h"
#import "HBDisbindBankCardConfirmParser.h"

#import "HBMyBankAccountCtrl.h"
#import "HBGetUserStatusManager.h"

#define leftMargan  (IsIphone4?15:(IsIphone5?15:(IsIphone6?15:15)))
#define leftMargan1 (IsIphone4?100:(IsIphone5?100:(IsIphone6?113:113)))

@interface HBMyBankReleaseCtrl ()
<UITextFieldDelegate>

@property (nonatomic, strong) UILabel *desLable;
@property (nonatomic, strong) UIView *desView;
@property (nonatomic, strong) UILabel *codeLable;
@property (nonatomic, strong) UITextField *codeTF;
@property (nonatomic, strong) UIButton *codeBtn;
@property (nonatomic, strong) UILabel *msgLable;
@property (nonatomic, strong) UILabel *safeLable;
@property (nonatomic, strong) UIButton *submitBtn;


@end

@implementation HBMyBankReleaseCtrl

#pragma mark -
#pragma mark - system

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)buildLayout
{
    [super buildLayout];
    self.title = @"我的银行卡";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextFieldTextDidChangeNotification object:nil];
    
    UITapGestureRecognizer *tapG = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickToEndEdit)];
    [self.view addGestureRecognizer:tapG];
    
    //    UIView *topBG =
    [self createSepratorLineWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30) backgroundColor:[LCCommon getColor:@"323232"] superView:self.view];
    
    self.desLable = [self createLableWithText:@"需要对您的手机号进行安全验证" font:[UIFont systemFontOfSize:12.0f] color:[LCCommon getColor:@"919191"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, 0, SCREEN_WIDTH-2*(leftMargan), 30) superView:self.view];
    
    
    //    UIView *midLine =
    [self createSepratorLineWithFrame:CGRectMake(leftMargan, 50, SCREEN_WIDTH-2*leftMargan, 1/([UIScreen mainScreen].scale)) backgroundColor:[LCCommon getColor:@"585858"] superView:self.view];
    self.codeLable = [self createLableWithText:@"验证码" font:[UIFont systemFontOfSize:16.0f] color:[LCCommon getColor:@"b1b1b1"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, 50, 95, 44) superView:self.view];
    self.codeTF = [self createTFWithPlaceHolder:@"请输入验证码" placeHolderColor:[LCCommon getColor:@"585858"] font:[UIFont systemFontOfSize:14] color:[LCCommon getColor:@"ffffff"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan1, 50, SCREEN_WIDTH-(leftMargan + leftMargan1)-105, 44) superView:self.view];
    
    UIView *buttomLine = [self createSepratorLineWithFrame:CGRectMake(leftMargan, 50+44, SCREEN_WIDTH-2*leftMargan, 1/([UIScreen mainScreen].scale)) backgroundColor:[LCCommon getColor:@"585858"] superView:self.view];
    
    self.codeBtn = [self createButtonWithFrame:CGRectMake(SCREEN_WIDTH-(leftMargan)-95, self.codeLable.y+5, 95, 33) normalBackgroundColor:[LCCommon getColor:@"f24545"] disabledBackgroundColor:[LCCommon getColor:@"bd3737"]  higlightedBackgroundColor:[LCCommon getColor:@"d43333"] normalFontColor:[LCCommon getColor:@"ffffff"] higlightedFontColor:[LCCommon getColor:@"ffffff"] disabledFontColor:[LCCommon getColor:@"fd7a7a"] title:@"发送验证码" contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter font:[UIFont systemFontOfSize:12] superView:self.view];
    [self createSepratorLineWithFrame:CGRectMake(SCREEN_WIDTH-2*leftMargan-95, self.codeBtn.y, 1/([UIScreen mainScreen].scale), self.codeBtn.height) backgroundColor:[LCCommon getColor:@"585858"] superView:self.view];
    
    
    self.safeLable = [self createLableWithText:@"短信验证码已经发送到你您的183******69手机" font:[UIFont systemFontOfSize:14.0f] color:[LCCommon getColor:@"777777"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, 50+44, SCREEN_WIDTH-2*leftMargan, 40) superView:self.view];
    
    
    self.msgLable = [self createLableWithText:@"" font:[UIFont systemFontOfSize:14.0f] color:[LCCommon getColor:@"fc353b"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, self.safeLable.y+self.safeLable.height, SCREEN_WIDTH-2*(leftMargan), 15) superView:self.view];
    self.msgLable.hidden = NO;
    
    self.submitBtn = [self createButtonWithFrame:CGRectMake(leftMargan, buttomLine.y+80, SCREEN_WIDTH-2*(leftMargan), 44) normalBackgroundColor:[LCCommon getColor:@"f24545"] disabledBackgroundColor:[LCCommon getColor:@"bd3737"] higlightedBackgroundColor:[LCCommon getColor:@"f24545"] normalFontColor:[LCCommon getColor:@"ffffff"] higlightedFontColor:[LCCommon getColor:@"ffffff"] disabledFontColor:[LCCommon getColor:@"fd7a7a"] title:@"下一步" contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter font:[UIFont systemFontOfSize:18] superView:self.view];
    [self reloadViewType];
    
    self.safeLable.text = [NSString stringWithFormat:@"短信验证码已经发送到你您的%@手机",self.phoneBind];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self makeTime];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -
#pragma mark - private

- (void)reloadViewType
{
}

- (void)makeTime{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSTimeInterval timeLast = [[[NSUserDefaults standardUserDefaults] objectForKey:RELEASEBANK_CODE_TIME] longLongValue];
        if (timeLast <= 0){
            
            self.codeBtn.enabled = YES;
//            [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
//            [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateDisabled];
            [self.codeBtn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
            [self.codeBtn setTitle:@"重新获取验证码" forState:UIControlStateDisabled];
            return;
        }
        NSTimeInterval now = [NSDate date].timeIntervalSince1970;
        if (now >= timeLast){
            
            self.codeBtn.enabled = YES;
            [self.codeBtn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
            [self.codeBtn setTitle:@"重新获取验证码" forState:UIControlStateDisabled];
            self.codeBtn.backgroundColor = [UIColor clearColor];
            return;
        }
        self.codeBtn.enabled = NO;
        [self.codeBtn setTitle:[NSString stringWithFormat:@"%d秒",(int)(timeLast- now)] forState:UIControlStateNormal];
        [self.codeBtn setTitle:[NSString stringWithFormat:@"%d秒",(int)(timeLast- now)] forState:UIControlStateDisabled];
        [self performSelector:@selector(makeTime) withObject:nil afterDelay:0.01];
    });
}




- (UIScrollView *)createScrollViewWithFrame:(CGRect)frame contentSize:(CGSize)contentSize andSuperView:(UIView *)superView
{
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:frame];
    scrollView.contentSize = contentSize;
    scrollView.bounces = NO;
    [superView addSubview:scrollView];
    return scrollView;
}

- (UITextField *)createTFWithPlaceHolder:(NSString *)placeHolder placeHolderColor:(UIColor *)placeColor font:(UIFont *)font color:(UIColor *)fontColor textAlignment:(NSTextAlignment)textAlignment frame:(CGRect)frame superView:(UIView *)superView
{
    UITextField *textField = [[UITextField alloc]initWithFrame:frame];
    textField.backgroundColor = [UIColor clearColor];
    textField.placeholder = placeHolder;
    textField.font = font;
    textField.textColor = fontColor;
    textField.textAlignment = textAlignment;
    textField.delegate = self;
    [textField setValue:placeColor forKeyPath:@"_placeholderLabel.textColor"];
    [superView addSubview:textField];
    return textField;
}

- (UILabel *)createLableWithText:(NSString *)text font:(UIFont *)font color:(UIColor *)fontColor textAlignment:(NSTextAlignment)textAlignment frame:(CGRect)frame superView:(UIView *)superView
{
    UILabel *lable = [[UILabel alloc]initWithFrame:frame];
    lable.backgroundColor = [UIColor clearColor];
    lable.text = text;
    lable.font = font;
    lable.textColor = fontColor;
    lable.textAlignment = textAlignment;
    [superView addSubview:lable];
    return lable;
}

- (UIView *)createSepratorLineWithFrame:(CGRect)frame backgroundColor:(UIColor *)bgColor superView:(UIView *)superView
{
    UIView *sepratorLine = [[UIView alloc]initWithFrame:frame];
    sepratorLine.backgroundColor = bgColor;
    [superView addSubview:sepratorLine];
    return sepratorLine;
}

- (UIButton *)createButtonWithFrame:(CGRect)frame normalBackgroundColor:(UIColor *)normalBGColor disabledBackgroundColor:(UIColor *)disabledBGColor higlightedBackgroundColor:(UIColor *)higlightedBGColor  normalFontColor:(UIColor *)normalFontColor higlightedFontColor:(UIColor *)higlightedFontColor disabledFontColor:(UIColor *)disabledFontColor title:(NSString *)title contentHorizontalAlignment:(UIControlContentHorizontalAlignment)textAlignment font:(UIFont *)font superView:(UIView *)superView
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setBackgroundColor:normalBGColor];
    [button setBackgroundColor:normalBGColor forState:UIControlStateNormal];
    [button setBackgroundColor:disabledBGColor forState:UIControlStateDisabled];
    [button setBackgroundColor:higlightedBGColor forState:UIControlStateHighlighted];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:normalFontColor forState:UIControlStateNormal];
    [button setTitleColor:disabledFontColor forState:UIControlStateDisabled];
    [button setTitleColor:higlightedFontColor forState:UIControlStateHighlighted];
    button.titleLabel.font = font;
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [button setContentHorizontalAlignment:textAlignment];
    [superView addSubview:button];
    button.enabled = NO;
    [button.layer setCornerRadius:4.0f];
    button.layer.masksToBounds = YES;
    return button;
}


#pragma mark -
#pragma mark - active


- (void)clickToEndEdit
{
    [self.codeTF resignFirstResponder];
    
}

- (void)clickButton:(UIButton *)sender
{
    if (sender == self.codeBtn)
    {
        [self requestToInvest];
    }
    else if (sender == self.submitBtn)
    {
        if ([CheckValid checkStrIsEmpty:self.codeTF.text])
        {
            [self.codeTF becomeFirstResponder];
            self.msgLable.hidden = NO;
            self.msgLable.text = @"验证码不能为空";
            
        }
        else if(![CheckValid isOnlyNumberAndCharString:self.codeTF.text limitedLengthMoreThan:4 lessThan:8])
        {
            //
            self.msgLable.hidden = NO;
            self.msgLable.text = @"请输入正确的验证码";
            [self.codeTF becomeFirstResponder];
        }
        else
        {
            [self requestToDisBindBank];
        }
        
    }
}


#pragma mark -
#pragma mark - delegate


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *toBeString = textField.text;
    
    UITextInputMode *currentInputMode = textField.textInputMode;
    NSString *lang = [currentInputMode primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length >= 6) {
                self.codeTF.text = [toBeString substringToIndex:6];
                if ([string isEqualToString:@""])
                {
                    return YES;
                }
                else
                {
                    return NO;
                }
            }
            
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length >= 6) {
            self.codeTF.text = [toBeString substringToIndex:6];
            if ([string isEqualToString:@""])
            {
                return YES;
            }
            else
            {
                return NO;
            }
        }
    }
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    //    [self showTFClearBtnWithTextField:textField];
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return YES;
}

#pragma mark -
#pragma mark - notify

-(void)textDidChange{
    
    self.msgLable.text = @"";
    
//    if (self.codeTF.text.length >= 4 ) {
//        self.submitBtn.enabled = YES;
//        
//    }else{
//        self.submitBtn.enabled = NO;
//        
//    }
    
    if (self.codeTF.text.length>0)
    {
        if (self.codeTF.text.length>=6)
        {
            if ([CheckValid isValidateCode:self.codeTF.text])
            {
                self.submitBtn.enabled = YES;
            }
            else
            {
                self.submitBtn.enabled = NO;
                self.msgLable.hidden = NO;
                self.msgLable.text = @"请输入正确的验证码";
            }
        }
        else
        {
            self.submitBtn.enabled = NO;
            self.msgLable.hidden = NO;
            self.msgLable.text = @"";
        }
        
    }
    else
    {
        self.msgLable.text = @"";
        self.submitBtn.enabled = NO;
    }
}

#pragma mark -
#pragma mark - request

- (void)requestToGetCode
{
    self.safeLable.hidden = NO;
//    self.safeLable.text = @"短信验证码已经发送到您的183*****69手机";
    self.safeLable.text = [NSString stringWithFormat:@"短信验证码已经发送到您的%@手机",self.phoneBind];
    
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970 + 60] forKey:RELEASEBANK_CODE_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self makeTime];
}

- (void)requestToInvest
{
    [CustomLoadingView showHudToView:self.view];
    HBDisbindBankCardParam *param = [[HBDisbindBankCardParam alloc]init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.bankCardId = self.bankCardId;
    HBDisbindBankCardParser *parser = [[HBDisbindBankCardParser alloc]init];
    [NetCenter postDataFromURL:Method_disbindBankCard params:param parser:parser result:^(ParserResult *myResult) {
        [CustomLoadingView hideHudForView:self.view];
        if (myResult.code==0)
        {
//            HBDisbindBankCardInfo *listInfo = (HBDisbindBankCardInfo *)myResult.result;
            
//            [HBGetUserStatusManager requestToGetUserStatusWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
//                
//            }];
//            [self.navigationController popToRootViewControllerAnimated:YES];
            
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970 + 60] forKey:RELEASEBANK_CODE_TIME];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self makeTime];
            
            
        }
        else
        {
//            DISSMISS_ERR(myResult.message);
            self.msgLable.text = myResult.message;
        }
        
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
//        DISSMISS_ERR([error description]);
        self.msgLable.text = [error description];
    }];
    
}

- (void)requestToDisBindBank
{
    [CustomLoadingView showHudToView:self.view];
    HBDisbindBankCardConfirmParam *param = [[HBDisbindBankCardConfirmParam alloc]init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.bankCardId = self.bankCardId;
    param.mobileCode = self.codeTF.text;
    HBDisbindBankCardConfirmParser *parser = [[HBDisbindBankCardConfirmParser alloc]init];
    [NetCenter postDataFromURL:Method_disbindBankCardConfirm params:param parser:parser result:^(ParserResult *myResult) {
        [CustomLoadingView hideHudForView:self.view];
        if (myResult.code==0)
        {
            //            HBDisbindBankCardInfo *listInfo = (HBDisbindBankCardInfo *)myResult.result;
            self.bankAccountCtrl.bindType = MyBankBindType_None;
            [HBGetUserStatusManager requestToGetUserStatusWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
                
            }];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            //            DISSMISS_ERR(myResult.message);
            self.msgLable.text = myResult.message;
        }
        
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        //        DISSMISS_ERR([error description]);
        self.msgLable.text = [error description];
    }];
    
}



@end
